package com.GUI.CustomControls;

import com.DAO.DAO;
import com.GUI.ChangeEmployeeListener;
import com.GUI.EmployeeTableObject;
import com.GUI.Popup;
import com.GUI.mainPanelCotroller;
import java.util.ArrayList;
import java.util.List;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableView;

/**
 *
 * @author Prezes
 */
public class DeleteButtonTableCell extends TableCell<EmployeeTableObject, String> {
    
        final private Button cellButton = new Button("usuń");
        private List<ChangeEmployeeListener> refreshTableListeners;
         
        public DeleteButtonTableCell()
        {
            refreshTableListeners = new ArrayList<>();
            refreshTableListeners.add(mainPanelCotroller.getInstance());
            
            cellButton.setOnAction(new EventHandler<ActionEvent>(){
 
                @Override
                public void handle(ActionEvent t) {
                    EmployeeTableObject eto = getTableView().getItems().get(getTableRow().getIndex());
                    
                    System.out.println("Usuwanie pracownika: " + eto.getName() + " " + eto.getSurname());
                    
                    Popup popup = new Popup();
                    try {
                        DAO dao = new DAO();
                        dao.removeEmployeeById(eto.getId());
                        popup.createPopupInfo("Pracownik usunięty!");
                        employeeChanged();
                    }
                    catch(Exception ex){
                        popup.createPopupInfo("Zaznacz najpierw pracownika do usunięcia!");
                    }
                }
            });
        }
 
        //Display button if the row is not empty
        @Override
        protected void updateItem(String t, boolean empty) 
        {
            super.updateItem(t, empty);
            if(!empty)
            {
                setGraphic(cellButton);
            }
        }
        
        private void employeeChanged() {
            for (ChangeEmployeeListener rtl : refreshTableListeners) { 
                rtl.employeeChangedEvent();
            }
        }
    }
